import { Button, Form, Input, Modal, Pagination, Select, Table, message } from 'antd';
import React, { useEffect, useState } from 'react';
import shallow from 'zustand/shallow';

import { classRoomsList, teacherList, coursesList, timeSlotList } from "../../../api/common";
import * as lessonsSort from '../../../api/course/lessonsSort'
import * as studentCourse from '../../../api/course/studentCourse'
import { SearchType } from '../../../api/course/lessonsSort';
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';
import useUserStore from '../../../store/useUserStore';

interface selectObject {
  classRoomsList: any[], // 教室
  teacherList: any[], //老师
  coursesList: any[] // 课程
  timeSlotList: any[] //时间
}

const CourseSelection: React.FC = () => {
  const { user } = useUserStore((state) => ({ user: state.user }), shallow)
  const { formRef } = useBseGeneraHook()

  const [selectList, setSelectList] = useState<selectObject>({
    classRoomsList: [],
    teacherList: [],
    coursesList: [],
    timeSlotList: []
  })
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(1)
  const [search, setSearch] = useState<SearchType>({ limit: 10, page: 1 })

  const getAllSelect = async () => {
    const teacher = await teacherList() as any
    const classRoom = await classRoomsList() as any
    const course = await coursesList() as any
    const timeSlot = await timeSlotList() as any
    setSelectList({
      classRoomsList: classRoom.data,
      teacherList: teacher.data,
      coursesList: course.data,
      timeSlotList: timeSlot.data
    })
  }

  const getList = async () => {
    const res = await lessonsSort.list(search) as any
    setList(res.data.content)
    setTotal(res.data.totalElements)
  }

  useEffect(() => {
    getAllSelect()
  }, [])


  useEffect(() => {
    getList()
  }, [search])

  const reset = () => {
    setSearch({ limit: 10, page: 1 })
    formRef.current?.resetFields();
  }
  const onSearch = (value: any) => {
    setSearch({ ...value, limit: 10, page: 1 })
  }
  const onPageChange = (page: number, pageSize: number) => {
    setSearch({ ...search, page: page || 1, limit: pageSize })
  }

  const filterSelect = (input: any, option: any) => {
    return option.children.indexOf(input) > 0
  }

  const selectCourse = async (value: any) => {
    const res = await studentCourse.created({
      student_id: user?.sid,
      lessonsSortId: value.id
    }).catch(e => console.log(e)) as any
    if (res.success) {
      message.success('添加成功')
    }
  }

  return (
    <>
      <div>
        <Form layout='inline' onFinish={onSearch} ref={formRef}>

          <Form.Item name="class_room_id">
            <Select style={{ width: '100px' }} allowClear placeholder="教室名" showSearch
              filterOption={filterSelect}>
              {
                selectList.classRoomsList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item name="teacher_id" >
            <Select style={{ width: '100px' }} allowClear placeholder="教师名" showSearch filterOption={filterSelect}>
              {
                selectList.teacherList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item name="course_id">
            <Select style={{ width: '100px' }} allowClear placeholder="课程名" showSearch filterOption={filterSelect}>
              {
                selectList.coursesList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="blur">
            <Input placeholder="综合搜索" allowClear />
          </Form.Item>



          <Form.Item >
            <Button type="primary" htmlType="submit">搜索</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="dashed" onClick={reset}>重置</Button>
          </Form.Item>
        </Form>
      </div >

      <div>
        <Table dataSource={list} pagination={false} rowKey="id"
          columns={[
            {
              title: '教室',
              key: 'class_room_name',
              render: (_: any, record: any) => (
                <><span>{record.classRoom.class_room_name}</span></>
              ),
            },
            {
              title: '课程属性',
              key: 'attribute',
              render: (_: any, record: any) => (
                <><span>{record.course.attribute}</span></>
              ),
            },
            {
              title: '课程名',
              key: 'attribute',
              render: (_: any, record: any) => (
                <><span>{record.course.name}</span></>
              ),
            },
            {
              title: '学分',
              key: 'credit',
              render: (_: any, record: any) => (
                <><span>{record.course.credit}</span></>
              ),
            },
            {
              title: '已选/人数',
              key: 'class_room_name',
              render: (_: any, record: any) => (
                <><span>{record.course.realityPeopleNumber} /{record.course.planPeopleNumber}</span></>
              ),
            },
            {
              title: '节数',
              dataIndex: 'several',
              key: 'several',
            },
            {
              title: '授课老师',
              key: 't_name',
              render: (_: any, record: any) => (
                <><span>{record.teacher.t_name}</span></>
              ),
            },
            {
              title: '每周',
              dataIndex: 'week',
              key: 'week',
            },
            {
              title: '上课时间',
              key: 'timeSlots',
              render: (_: any, record: any) => (
                <><span> {record.timeSlots[0].start_date + "-" + record.timeSlots[record.timeSlots.length - 1].start_date}</span></>
              ),
            },
            {
              title: '操作',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <Button type="primary" onClick={() => selectCourse(record)}>选择课程</Button>
                </>
              ),
            },
          ]}
        />
      </div>
      <div><Pagination showSizeChanger={true} total={total} onChange={onPageChange} /></div>


    </>
  );
}
export default CourseSelection